import {Component, OnInit, ViewChild} from '@angular/core';
import {Router} from '@angular/router';
import {RoleService} from '../../../lib/service/tuike/role.service';
import {RoleList, RoleInfo, AddRole, EditRole} from "./role";
import {ModalDirective} from 'ngx-bootstrap';
import {TreeData} from '../p-tree/tree-model';
import {PTreeComponent} from "../p-tree/p-tree.component";
import {tuikeSystemUrl} from "../../../../config/api";

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.scss'],
  providers: [RoleService]
})
export class RoleComponent implements OnInit {

  totalItems: number;
  currentPage = 1;
  itemsPerPage = 12;
  name: string;
  belong: string;
  orderField: string;
  orderSort: string;
  type: string;
  message: string;
  isShow = false;
  roleInfo = new RoleInfo();
  roleList = new RoleList();
  addRole = new AddRole();
  editRole = new EditRole();
  setId: number;
  permissionGroup = [];
  permissionCheck: any = [];
  permissionList: any = [];
  _isSpinning = false;
  editId = null;
  delId;
  permission = [];
  nameError = false;

  @ViewChild('t') t: PTreeComponent;

  singleCheckedNodeId: string = '2';
  ids = [];
  p_list = [];
  role_status = false;

  @ViewChild('addModal') public addModal: ModalDirective;
  @ViewChild('editModal') public editModal: ModalDirective;
  @ViewChild('staticModal') public staticModal: ModalDirective;
  @ViewChild('deleteModal') public delModal: ModalDirective;

  constructor(private router: Router,
              private roleService: RoleService) {
    this.name = '';
    this.belong = '';
    this.orderField = '';
    this.orderSort = '';
  }

  ngOnInit() {
    this.getRoleList();
    this.getAllRole();
    this.getPermissionTree();
  }

  onClick(item) {
    console.info(item);
  }

  checkLength(e) {
    if(e.length < 3) {
      this.nameError = true;
    } else {
      this.nameError = false;
    }
  }


  checkednum = 0;

  showAddModal() {
    this.addRole = new AddRole();
    this.editId = null;
    if (this.p_list.length > 0) {
      this.clearAllChecked(this.p_list);
    }
    this.addModal.show();
  }

  checkNumCount(arr) {
    arr.map((e) => {
      ++this.checkednum;
      console.log(e.isChecked);
      if (e.isChecked) {
        this.ids.push(e.id);
      }
      if (e.children) {
        this.checkNumCount(e.children);
      }
    });
  }

  pushCheckedIds(arr) {
    arr.map((e, i) => {
      if (e.isChecked) {
        if (this.ids.length == 0) {
          let flag = true;
          this.ids.map((e1, i) => {
            console.log(e1, e.id);
            if (e1 == e.id) {
              flag = false;
            }
          });
          if (flag) {
            this.ids.push(e.id);
          }
        } else {
          this.ids.push(e.id);
        }
      }
      if (e.children) {
        this.pushCheckedIds(e.children);
      }
    })
  };

  renderCheckedIds(arr) {
    arr.map((e, i) => {
      this.ids.map((e1, i1) => {
        if (e.id == e1) {
          e['isChecked'] = true;
        }
      });
      if (e.children) {
        this.renderCheckedIds(e.children);
      }
    })
  }

  clearAllChecked(arr) {
    arr.map((e, i) => {
      e['isChecked'] = false;
      if (e.children) {
        this.clearAllChecked(e.children);
      }
    })
  }

  waitRecursive() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        this.pushCheckedIds(this.p_list);
        resolve();
      }, 100);
    })
  }

  onCheckChanged(item) {
    this.ids = [];
    this.waitRecursive().then(() => {
      console.log(this.ids);
    });
  }

  /*获取权限列表*/
  getPermissionsList() {
    this.roleService.getPermissionList(this.currentPage, this.itemsPerPage).subscribe(res => {
      console.log(res);
    })
  }

  /*获取角色列表*/
  getRoleList() {
    this._isSpinning = true;
    this.roleService.getRoleList(this.currentPage, this.itemsPerPage).subscribe(
      data => {
        if (data.code === 200) {
          this.roleList.list = data.data.data;
          this.currentPage = data.data.currentPage;
          this.totalItems = data.data.total;
          this._isSpinning = false;
        }
      }
    );
  }

  /*获取所有角色*/
  getAllRole() {
    this.roleService.getAllRole().subscribe(res => {
      console.log(res);
    })
  }

  /*角色详情*/
  getRoleInfo(id): void {
    this.roleService.getRoleInfo(id).subscribe(
      res => {
        let data = res.data;
        this.addRole.description = data.description;
        this.addRole.role_name = data.role_name;
        this.role_status = data.role_status;
        this.ids = data.permission;
        if (this.p_list.length > 0) {
          this.clearAllChecked(this.p_list);
          this.renderCheckedIds(this.p_list);
        }
      }
    );
  }

  /*角色添加*/
  addRoleSubmit() {
    this.addRole['permission_ids'] = JSON.stringify(this.ids).substring(1, JSON.stringify(this.ids).length - 1);
    this.roleService.addRole(this.addRole).subscribe(
      data => {
        if (data.code === 200) {
          this.type = 'success';
          this.message = '添加成功';
          this.isShow = true;
          this.addModal.hide();
          this.getRoleList();
        }
      }
    );
  }

  editRoleSubmit() {
    // this.addRole['permission_ids'] = JSON.stringify(this.ids).substring(1,JSON.stringify(this.ids).length - 1);
    this.addRole['permission_ids'] = this.ids.join(',');
    this.addRole['id'] = this.editId;
    this.addRole['role_status'] = this.role_status ? 1 : 0;
    this.roleService.editRole(this.addRole).subscribe(
      data => {
        if (data.code === 200) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.addModal.hide();
          this.getRoleList();
        }
      }
    );
  }


  showEditModal(id) {
    this.editId = id;
    this.getRoleInfo(id);
    this.addModal.show();
  }

  showDelModal(id) {
    this.delId = id;
    this.delModal.show();
  }

  delRole() {
    this.roleService.delRole({'id': this.delId}).subscribe(res => {
      if (res.code === 200) {
        this.isShow = true;
        this.message = '删除成功';
        this.type = 'success';
        this.delModal.hide();
        this.getRoleList();
      } else {
        this.isShow = true;
        this.message = res.message;
        this.type = 'error';
      }
    })
  }


  renderList(arr, data) {
    if (arr.length == 0) {
      arr.push({
        id: data.id,
        parentId: 0,
        isExpend: true,
        isChecked: false,
        name: data.permission_name
      })
    } else {
      arr[arr.length - 1]['children'] = [];
      data.map((e, i) => {
        arr[arr.length - 1]['children'].push({
          id: e.id,
          parentId: e.parent_id,
          isExpend: true,
          isChecked: false,
          name: e.permission_name
        })
      });
    }
    ;
    this.renderList(arr[arr.length - 1]['children'], data.data);
  }

  getPermissionTree() {
    this.roleService.getPermissionTree().subscribe(
      data => {
        if (data.code === 200) {
          this.permissionGroup = data.data.children;
          this.p_list = this.permissionGroup;
        }
      })
  }

  getPermissionGroup(id) {
    this.setId = id;
    this.roleService.getPermissionTree().subscribe(
      data => {
        if (data.code === 200) {
          this.permissionGroup = data.data.children;
          this.p_list = this.permissionGroup;
        }
      }
    );
  }

  giveRolePermission(id) {
    this.roleService.getRolePermission(id).subscribe(
      data => {
        this.permissionCheck = data.data;
        this.permissionGroup.forEach(function (value, index, array) {
          value.data.forEach(function (value2, index2, array2) {
            value2.checked = true;
            if (data.data.indexOf(value2.id) === -1) {
              value2.checked = false;
            }
          });
        });
      }
    );
  }

  rolePermissionEdit(): void {
    const permission = JSON.stringify(this.permissionCheck);
    this.roleService.setRolePermission(permission, this.setId).subscribe(
      data => {
        if (data.code === 2000) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.staticModal.hide();
          this.getRoleList();
        }
      }
    );
  }

  checkRolePermission(e, id) {
    if (e.target.checked) {
      this.permissionCheck.push(id);
    } else {
      for (let i = 0; i < this.permissionCheck.length; i++) {
        if (this.permissionCheck[i] === id) {
          this.permissionCheck.splice(i, 1);
          break;
        }
      }
    }
  };

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.currentPage = event.page;
    this.getRoleList();
  }

  promptIsShow(event: any): void {
    this.isShow = event;
  }
}
